import { wisdomErrors } from "@/api";
import {
  Field,
  QueryField,
  usePagination,
  useQueryArea,
  useTableArea,
} from "@/composables";
import parseTime from "@/utils/parseTime";
import { ElMessage } from "element-plus";
import { Fragment, defineComponent, onMounted, ref } from "vue";

export default defineComponent({
  name: "ErrorLogs",
  setup() {
    const tableData = ref<any[]>([]);
    const tableFields: Field[] = [
      {
        prop: "bid",
        title: "设备id",
      },
      {
        prop: "name",
        title: "设备名称",
      },
      {
        prop: "type",
        title: "异常类型",
      },
      {
        prop: "gps",
        title: "坐标x",
      },
      {
        prop: "frequency",
        title: "异常次数",
      },
      {
        prop: "createTime",
        title: "异常时间",
        slot: (row) => <span>{parseTime(row.createTime)}</span>,
      },
      {
        title: "操作",
        slot: (row) => (
          <Fragment>
            <el-button
              link
              type="primary"
              onClick={() => handleNavigation(row)}
            >
              一键导航
            </el-button>
          </Fragment>
        ),
      },
    ];
    const queryFields: QueryField[] = [
      {
        prop: "name",
        title: "设备名称",
      },
      {
        prop: "bid",
        title: "设备id",
      },
      {
        prop: "type",
        title: "异常类型",
      },
    ];
    const initialParams = {
      page: 1,
      limit: 10,
    };

    async function getList() {
      loading.value = true;
      try {
        const res = await wisdomErrors.queryAll(params.value);
        tableData.value = res.data?.list || [];
        total.value = res.data?.total || 0;
      } finally {
        loading.value = false;
      }
    }
    const total = ref(0);
    const { QueryArea, params } = useQueryArea();
    const { TableArea, loading } = useTableArea();
    const { Pagination } = usePagination();

    function handleQueryReset(): void {
      params.value = { ...initialParams };
      getList();
    }

    async function handleNavigation(row: any) {
      loading.value = true;
      try {
        const { message } = (await wisdomErrors.navigation({
          deviceId: row.bid,
          mid: row.mid,
        })) as any;
        ElMessage({ type: "success", message });
        getList();
      } finally {
        loading.value = false;
      }
    }

    onMounted(() => {
      handleQueryReset();
    });

    return () => (
      <Fragment>
        <QueryArea
          queryFields={queryFields}
          onQuery={getList}
          onReset={handleQueryReset}
        />
        <TableArea tableFields={tableFields} tableData={tableData.value} />
        <Pagination total={total.value} params={params} onChange={getList} />
      </Fragment>
    );
  },
});
